'use strict';
const db = uniCloud.database();
const dbCmd = db.command;
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event);
	let res = '';
	if(event.anonymousCode){
		let appid = "ttc5beb3035a858126";
		let secret = "5a05a2ad3efd6975ca8a57a83430df2098911b11";
		let url =
			"https://developer.toutiao.com/api/apps/v2/jscode2session";
		res = await uniCloud.httpclient.request(
			url, {
				timeout: 10000,
				method:'POST',
				data:{
					appid:appid,
					secret:secret,
					code:event.code
				},
				headers: {},
				contentType: 'json', // 指定以application/json发送data内的数据
				dataType: 'json' // 指定返回值为json格式，自动进行parse
			})
		console.log('res', res);
		res = res.data.data;
		if(res.openid){
			await saveSql({
				openId:res.openid,
				type:'tt'
			})
		}
	}else if (event.code) {
		let appid = "wx4b2f52e300112fea";
		let secret = "50531d3f8ae9a68361925a75ece579cb";
		let url =
			"https://api.weixin.qq.com/sns/jscode2session?appid=" +
			appid +
			"&secret=" +
			secret +
			"&js_code=" +
			event.code +
			"&grant_type=authorization_code";
		res = await uniCloud.httpclient.request(
			url, {
				timeout: 10000,
				headers: {},
				contentType: 'json', // 指定以application/json发送data内的数据
				dataType: 'json' // 指定返回值为json格式，自动进行parse
			})
		console.log('res', res);
		res = res.data;
		if(res.openid){
			let saveItem = {
				openId:res.openid,
				type:'wx'
			};
			if(event.inviteId){
				saveItem['inviteId'] = event.inviteId;
			}
			await saveSql(saveItem);
		}
	}

	//返回数据给客户端
	return res;
};

async function saveSql(findItem) {
	const collectionallList = db.collection('userInfo');
	const docListallList = await collectionallList.where({
		openId: findItem['openId']
	}).get();
	if (!docListallList.data || docListallList.data.length === 0) {
		console.log('openId不存在！存入今日列表');
		let tempRes = await collectionallList.add({
			...findItem,
			createTime:new Date().getTime(),
			updateTime: new Date().getTime(),
			dayHasFinish:'',
			correctNum:0,
			errorNum:0,
			scoreNum:0,
			allFinishTime:0
		});
		console.log('tempRes',tempRes);
		
		if(findItem.inviteId){
			await db.collection('friendList').add({
				inviteId:findItem.inviteId,
				myId:tempRes.id,
				createTime:new Date().getTime(),
				updateTime: new Date().getTime(),
				giveBalance:0
			});
		}
		
	} else {
		console.log('内容已存在');
		// await collectionallList.doc(docListallList.data[0]._id).update(findItem);
	}
}